package com.yl.module.common.controller;

import com.yl.module.base.controller.BaseController;
import com.yl.module.base.model.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Todo 可以跨域上传
 * @Author jiangtao
 * @CreateBy 2020-02-18 4:14 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Slf4j
@Controller
@RequestMapping("upload")
public class UploadController extends BaseController {

    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMM");

    /**
     * 上传普通图片
     * @param file
     * @param model
     * @param req
     * @return
     */
    @PostMapping("image")
    public R image(@RequestParam(value = "file") MultipartFile file,
                   Model model,
                   HttpServletRequest req) {

        if (file.isEmpty()) {
            return error(500, "图片不能为空");
        }

        String basePath = req.getSession().getServletContext().getRealPath("upload");

        StringBuffer absolutePath = new StringBuffer();
        StringBuffer relativePath = new StringBuffer();
        absolutePath.append(basePath.replace("\\", "/")).append("/images");
        relativePath.append("upload/").append("/images");

        String dir = (String)model.getAttribute("dir");
        if (StringUtils.isNotEmpty(dir)) {
            absolutePath.append("/").append(dir);
            relativePath.append("/").append(dir);
        }
        String time = dtf.format(LocalDateTime.now());
        absolutePath.append("/").append(time).append("/");
        relativePath.append("/").append(time).append("/");

        //判断文件夹是否存在
        File fileDir = new File(absolutePath.toString());
        if(!fileDir.exists()) {
            fileDir.mkdirs();
        }

        //文件名 扩展名
        String orgName = file.getOriginalFilename();
        String ext = orgName.substring(orgName.lastIndexOf(".") + 1);
        if (!"png".equalsIgnoreCase(ext) &&
            !"jpg".equalsIgnoreCase(ext) &&
            !"jpeg".equalsIgnoreCase(ext) &&
            !"gif".equalsIgnoreCase(ext)) {

        }


        //新文件名
        String newName = (UUID.randomUUID().toString()).replace("-", "") + "." + ext;



        return success();
    }

    /**
     * 上传Base64编码图片
     * @param file
     * @param model
     * @param req
     * @return
     */
    @PostMapping("base64")
    public R base64(@RequestParam(value = "file") MultipartFile file,
                   Model model,
                   HttpServletRequest req) {
        return success();
    }

    /**
     * 上传普通文件
     * @param file
     * @param model
     * @param req
     * @return
     */
    @PostMapping("file")
    public R file(@RequestParam(value = "base64") String base64,
                    Model model,
                    HttpServletRequest req) throws IOException {
        // Base64编码后的图片上传后，先判断后缀（如 png 图片编码后前缀就会是 data:image/png;base64,...）
        // 校验 data:image/png;base64
        final File tempFile = new File("F:/app/chapter16/test.png");
        String[] d = base64.split("base64,");
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes, tempFile);

        return success();
    }













    private String uploadDirectory() {
        String projectPath = System.getProperty("user.dir");
        projectPath = projectPath.replace("\\", "/");
        return projectPath + "/src/main/resources/";
    }




}
